package com.zhitan.ems.app.iot.controller;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhitan.ems.app.iot.entity.DeviceEntity;
import com.zhitan.ems.app.iot.entity.DevicePropertyDataEntity;
import com.zhitan.ems.app.iot.entity.DevicePropertyEntity;
import com.zhitan.ems.app.iot.entity.DeviceTypeEntity;
import com.zhitan.ems.app.iot.entity.ProductEntity;
import com.zhitan.ems.app.iot.service.DeviceGroupService;
import com.zhitan.ems.app.iot.service.DevicePropertyDataService;
import com.zhitan.ems.app.iot.service.DevicePropertyService;
import com.zhitan.ems.app.iot.service.DeviceService;
import com.zhitan.ems.app.iot.service.DeviceTypeService;
import com.zhitan.ems.app.iot.service.ProductService;
import com.zhitan.ems.app.iot.vo.DeviceGroupVO;
import com.zhitan.ems.app.iot.vo.DeviceOnlineVO;
import com.zhitan.ems.app.iot.vo.DeviceVO;
import com.zhitan.ems.app.iot.wrapper.DeviceWrapper;
import com.zhitan.ems.common.annotation.Log;
import com.zhitan.ems.common.core.controller.BaseController;
import com.zhitan.ems.common.core.domain.R;
import com.zhitan.ems.common.enums.BusinessType;
import com.zhitan.ems.common.utils.DateUtils;
import com.zhitan.ems.common.utils.StringUtils;
import com.zhitan.ems.common.utils.poi.ExcelUtil;
import com.zhitan.ems.framework.core.vo.VPage;
import com.zhitan.ems.framework.core.vo.VQueryKit;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
 * 设备
 * @author zhitan
 * 
 * @date 2025-09-19 22:15:46
 */
@Api(tags = "设备", value = "设备")
@RestController
@RequestMapping("intra/iot/device")
public class DeviceController extends BaseController{
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DevicePropertyService devicePropertyService;
    @Autowired
    private DevicePropertyDataService devicePropertyDataService;
    @Autowired
    private DeviceGroupService deviceGroupService;
    @Autowired
    private DeviceTypeService deviceTypeService;
    @Autowired
    private ProductService productService;
    /**
     * 列表
     */
    @ApiOperation(value = "列表", response = VPage.class)
    @ApiImplicitParams({
		        @ApiImplicitParam(name = "name", value = "标题",  paramType = "query", required = false, dataType =  "String"),
		})
    @GetMapping("/browse")
    @PreAuthorize("@ss.hasPermi('iot:device:list')")
    public R<VPage<DeviceVO>> browse(@RequestParam Map<String, Object> params){
        QueryWrapper<DeviceEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name","deviceName"), DeviceEntity.class);
        queryWrapper.orderByDesc("id");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"device_name", params.get("name"));
         queryWrapper.like(StringUtils.isNotNull(params.get("deviceName")),"device_name", params.get("deviceName"));
        IPage<DeviceEntity> pages = deviceService.page(VQueryKit.getPage(params), queryWrapper);
        return R.data(DeviceWrapper.build().toVPageVO(pages));
    }
    @ApiOperation(value = "所有列表", response = VPage.class)
    @ApiImplicitParams({
		        @ApiImplicitParam(name = "name", value = "标题",  paramType = "query", required = false, dataType =  "String"),
		})
    @GetMapping("/listAll")
    @PreAuthorize("@ss.hasPermi('iot:device:list')")
    public R<List<DeviceVO>> listAll(@RequestParam Map<String, Object> params){
        QueryWrapper<DeviceEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name","deviceName"), DeviceEntity.class);
        queryWrapper.orderByDesc("id");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"device_name", params.get("name"));
         queryWrapper.like(StringUtils.isNotNull(params.get("deviceName")),"device_name", params.get("deviceName"));
         List<DeviceEntity> list = deviceService.list(queryWrapper);
        return R.data(DeviceWrapper.build().listVO(list));
    }
    /**
     * 列表
     */
    @ApiOperation(value = "列表", response = VPage.class)
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "name", value = "标题",  paramType = "query", required = false, dataType =  "String"),
    })
    @GetMapping("/browseState")
    @PreAuthorize("@ss.hasPermi('iot:device:list')")
    public R<VPage<DeviceOnlineVO>> browseState(@RequestParam Map<String, Object> params){
    	QueryWrapper<DeviceEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name","deviceName"), DeviceEntity.class);
    	queryWrapper.select("id,device_name as deviceName,device_code as deviceCode,online_state onlineState ,online_time as onlineTime,offline_time as offlineTime");
    	queryWrapper.orderByDesc("online_time");
    	queryWrapper.like(StringUtils.isNotNull(params.get("name")),"device_name", params.get("name"));
    	queryWrapper.like(StringUtils.isNotNull(params.get("deviceName")),"device_name", params.get("deviceName"));
    	IPage<DeviceEntity> pages = deviceService.page(VQueryKit.getPage(params), queryWrapper);
    	return R.data(DeviceWrapper.build().toVPageOnlineVO(pages));
    }
    @ApiOperation(value = "列表", response = VPage.class)
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "name", value = "标题",  paramType = "query", required = false, dataType =  "String"),
    })
    @GetMapping("/getPieState")
    @PreAuthorize("@ss.hasPermi('iot:device:list')")
    public R<Map<String, Object>> getPieState(@RequestParam Map<String, Object> params){
    	return R.data(deviceService.getOnlineStatusStatistics(params));
    }
    @GetMapping("/listStat")
    @PreAuthorize("@ss.hasPermi('iot:device:list')")
    public R<Map<String, Object>> listStat(@RequestParam Map<String, Object> params)throws ParseException{
         QueryWrapper<DeviceEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), DeviceEntity.class);
         queryWrapper.select("count(id) as total,sum(id) as all");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"device_name", params.get("name"));
        if(params.containsKey("createDate")) {
            queryWrapper.between("create_at",
                    DateUtils.getStartOfDate(DateUtils.str_ToDate(params.get("createDate").toString())),
                    DateUtils.getEndOfDate(DateUtils.str_ToDate(params.get("createDate").toString()))
              );   
        }
        Map<String, Object>  stat=deviceService.getMap(queryWrapper);
        return R.data(stat);
    }
    @ApiOperation("导出")
	@Log(title = "参数管理", businessType = BusinessType.EXPORT)
	@PreAuthorize("@ss.hasPermi('iot:device:list')")
	@PostMapping("/toExport")
	public void toExport(HttpServletResponse response, @RequestParam Map<String, Object> params) {
		QueryWrapper<DeviceEntity> queryWrapper = VQueryKit.getQueryWrapperByMap(params, Arrays.asList("name"),
				DeviceEntity.class);
		queryWrapper.orderByDesc("id");
		queryWrapper.like(StringUtils.isNotNull(params.get("name")), "device_name", params.get("name"));
		 List<DeviceEntity> iotDeviceList = deviceService.list(queryWrapper);
		ExcelUtil<DeviceEntity> util = new ExcelUtil<>(DeviceEntity.class);
		util.exportExcel(response, iotDeviceList, "参数数据");
	}
    /**
     * 信息
     */
    @ApiOperation(value = "根据类型获取空设备", response = DeviceVO.class)
    @GetMapping("/getEmptyByType")
    @PreAuthorize("@ss.hasPermi('iot:device:save')")
    public R<DeviceVO> getEmptyByType(@RequestParam Long typeId){
    	DeviceVO deviceVO=new DeviceVO();
		deviceVO.setDeviceTypeId(typeId);
		List<DevicePropertyEntity> devicePropertyList=devicePropertyService.getByTypeId(typeId, 0);
		List<DevicePropertyDataEntity> devicePropertyDataList=new ArrayList<DevicePropertyDataEntity>();
		HashMap<String, DevicePropertyDataEntity> dataMap=new HashMap<String, DevicePropertyDataEntity>();
		for(DevicePropertyDataEntity item:devicePropertyDataList) {
			if(item.getPropertyCode()!=null) {
				dataMap.put(item.getPropertyCode(), item);
			}
		}
		for(DevicePropertyEntity item:devicePropertyList) {
			if(!dataMap.containsKey(item.getDataCode())) {
				DevicePropertyDataEntity e=new DevicePropertyDataEntity();
				e.setDataType(0);
				e.setIsDelete(0);
				e.setPropertyCode(item.getDataCode());
				e.setPropertyName(item.getName());
				e.setPropertyId(item.getId());
				e.setValueString("");
				e.setDataFormContent(item.getDataFormContent());
				e.setDataFormType(item.getDataFormType());
				e.setDataMultiple(item.getDataMultiple());
				devicePropertyDataList.add(e);
			}
		}
		deviceVO.setDevicePropertyDataList(devicePropertyDataList);
	    return R.data(deviceVO);
    }
//    @ApiOperation(value = "获取系统所有摄像头设备信息", response = DeviceVO.class)
//    @GetMapping("/showVideoDeviceList")
//    public R<List<DeviceInfoVO> > showVideoDeviceList()throws ParseException, ClientException{
//    	  OauthApi auApi=new OauthApi();
//    	  IccTokenResponse.IccToken iccToken= auApi.getTokenInfo();
//    	  DeviceApi deviceApi=new DeviceApi();
//    	  DevicePageResponse devicePageResponse =deviceApi.getDeviceList();
//    	RealTimePreviewApi realTimePreviewApi = new RealTimePreviewApi();
//		List<DeviceInfoVO> pageData=devicePageResponse.getData().getPageData();
//    	for(DeviceInfoVO item:pageData) {
//			RtspUrlRequest.Data data = new RtspUrlRequest.Data();
//			String deviceCode=item.getDeviceCode();
//			if(!deviceCode.contains("$")) {
//				deviceCode=deviceCode+"$1$0$0";
//			}
//			HlsUrlRequest.Data hData = new HlsUrlRequest.Data();
//			hData.setChannelId(deviceCode);
//			hData.setStreamType("1");
//			hData.setType("hls");
//			HlsUrlRequest hlsUrlRequest=new HlsUrlRequest();
//			hlsUrlRequest.setData(hData);
//			HlsUrlResponse hlsUrlResponse=realTimePreviewApi.getHlsUrl(hlsUrlRequest);
//			item.setHlsUrlResponse(hlsUrlResponse);
//			try {
//				String rtspUrl = hlsUrlResponse.getData().getUrl() + "?token=" + iccToken.getAccess_token();
//				item.setShowUrl(rtspUrl);	
//			} catch (Exception e) {
//			} 
//    	}
//    	return R.data(pageData);
//    }
    @ApiOperation(value = "获取设备数据属性", response = DeviceVO.class)
    @PreAuthorize("@ss.hasPermi('iot:device:info')")
    @GetMapping("/getDataDetail/{id}")
    public R<DeviceVO> getDataDetail(@PathVariable("id") Long id){
    	DeviceEntity device = deviceService.getById(id);
    	DeviceVO deviceVO=DeviceWrapper.build().entityVO(device);
    	List<DevicePropertyEntity> devicePropertyList=devicePropertyService.getByTypeId(device.getDeviceTypeId(), 1);
    	deviceVO.setProDataPertyList(devicePropertyList);
    	return R.data(deviceVO);
    }
    /**
     * 信息
     */
    @ApiOperation(value = "信息", response = DeviceVO.class)
    @PreAuthorize("@ss.hasPermi('iot:device:info')")
    @GetMapping("/detail/{id}")
    public R<DeviceVO> detail(@PathVariable("id") Long id){
    	DeviceEntity device = deviceService.getById(id);
    	DeviceVO deviceVO=DeviceWrapper.build().entityVO(device);
    	//@ApiModelProperty("类型：0 硬件属性 1 数据属性")
    	List<DevicePropertyEntity> devicePropertyList=devicePropertyService.getByTypeId(device.getDeviceTypeId(), 0);
    	List<DevicePropertyDataEntity> devicePropertyDataList=devicePropertyDataService.getByDeviceId(id);
    	HashMap<String, DevicePropertyDataEntity> dataMap=new HashMap<String, DevicePropertyDataEntity>();
    	for(DevicePropertyDataEntity item:devicePropertyDataList) {
    		if(item.getPropertyCode()!=null) {
    			dataMap.put(item.getPropertyCode(), item);
    		}
    	}
    	for(DevicePropertyEntity item:devicePropertyList) {
    		if(!dataMap.containsKey(item.getDataCode())) {
    			DevicePropertyDataEntity e=new DevicePropertyDataEntity();
    			e.setDeviceId(id);
    			e.setDataType(0);
    			e.setIsDelete(0);
    			e.setPropertyCode(item.getDataCode());
    			e.setPropertyName(item.getName());
    			e.setPropertyId(item.getId());
    			e.setKind(item.getKind());
    			devicePropertyDataList.add(e);
    		}
    	}
    	deviceVO.setDevicePropertyDataList(devicePropertyDataList);
    	if(deviceVO.getIsVirtual()!=null&&deviceVO.getIsVirtual()==1) {
    		List<DeviceGroupVO>  deviceGroupVOs=deviceGroupService.getByDeviceId(id,1);
    		deviceVO.setDeviceGroupVOs(deviceGroupVOs);
    	}
    	
//    	if(monitorDevice.getVideoType()!=null&&monitorDevice.getVideoType()==1) {
//    		 OauthApi auApi=new OauthApi();
//       	  IccTokenResponse.IccToken iccToken=null;
//       	  RealTimePreviewApi realTimePreviewApi = new RealTimePreviewApi();
//	    	  try {
//				iccToken= auApi.getTokenInfo();
//				deviceVO.setVideoCodeAShowUrl(DahuaKit.getShowUrlByCode(iccToken, realTimePreviewApi, monitorDevice.getVideoCodeA()));
//	   			deviceVO.setVideoCodeBShowUrl(DahuaKit.getShowUrlByCode(iccToken, realTimePreviewApi, monitorDevice.getVideoCodeB()));
//	   			deviceVO.setVideoCodeCShowUrl(DahuaKit.getShowUrlByCode(iccToken, realTimePreviewApi, monitorDevice.getVideoCodeC()));
//	   			deviceVO.setVideoCodeDShowUrl(DahuaKit.getShowUrlByCode(iccToken, realTimePreviewApi, monitorDevice.getVideoCodeD()));
//			} catch (ClientException e) {
//			}
//    	}
//    	 if(device.getDeviceType()!=null&&device.getDeviceType()==800) {//摄像头
//       	  OauthApi auApi=new OauthApi();
//       	  IccTokenResponse.IccToken iccToken=null;
//       	  RealTimePreviewApi realTimePreviewApi = new RealTimePreviewApi();
//	    	  try {
//				iccToken= auApi.getTokenInfo();
//				String deviceCode=monitorDevice.getDeviceCode();
//    			String rtspUrl =DahuaKit.getShowUrlByCode(iccToken, realTimePreviewApi, deviceCode);
//    			deviceVO.setShowUrl(rtspUrl);	
//			} catch (ClientException e) {
//			}
//          }
    	return R.data(deviceVO);
    }
   
     /**
     * 保存&更新 
     */
    @Log(title = "设备", businessType = BusinessType.ADDANDEDIT)
    @ApiOperation(value = "保存&更新", response = Boolean.class)
    @PostMapping("/submit")
    @PreAuthorize("@ss.hasPermi('iot:device:save')")
    public R<DeviceVO> submit(@Valid @RequestBody DeviceVO device){
    	 if(device.getId()==null) {
           return add(device);
         }else {
           return edit(device);
        }
    }
    @Log(title = "设备", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增", response = Boolean.class)
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('iot:device:save')")
    public R<DeviceVO> add(@Valid @RequestBody DeviceVO device){
   		if(device.getId()==null) {
            device.setCreateAt(new Date());
            device.setIsDelete(0);
            device.setUpdateAt(new Date());
        } 
   		if(device.getDeviceTypeId()!=null) {
   			DeviceTypeEntity deviceType =deviceTypeService.getById(device.getDeviceTypeId());
 			if(deviceType!=null) {
 				device.setDeviceType(deviceType.getType());
 				device.setDeviceTypeName(deviceType.getName());
 				if(device.getId()==null) {
 	 				deviceType.setTotalSum(deviceType.getTotalSum()+1);
 	 	 			deviceTypeService.updateById(deviceType);
 	 			}
 			}
 		}
// 		if(device.getCateId()!=null) {
// 			CategoryEntity monitorCategory =monitorCategoryService.getById(device.getCateId());
// 			if(monitorCategory!=null) {
// 				device.setCateName(monitorCategory.getName());
// 			}
// 		}
 		if(device.getProductId()!=null) {
 			ProductEntity product =productService.getById(device.getProductId());
 			if(product!=null) {
 				device.setProductName(product.getProductName());
 			}
 		}
    	if(deviceService.save(device)) {
    		List<DevicePropertyDataEntity> devicePropertyDataList=device.getDevicePropertyDataList();
    		for(DevicePropertyDataEntity item:devicePropertyDataList) {
    				item.setDeviceId(device.getId());
    				if(item.getId()==null) {
    					item.setCreateAt(new Date());
    					item.setIsDelete(0);
    		        } 
    				item.setUpdateAt(new Date());
        	}
    		devicePropertyDataService.saveOrUpdateBatch(devicePropertyDataList);
    		
    		List<DeviceGroupVO>  deviceGroupVOs=device.getDeviceGroupVOs();
    		if(deviceGroupVOs!=null&&deviceGroupVOs.size()>0) {
    			deviceGroupService.modState(null,device.getId(),1, 0);
    			for(DeviceGroupVO item:deviceGroupVOs) {
    				item.setDeviceId(device.getId());
    				if(item.getId()==null) {
    					item.setCreateAt(new Date());
    					item.setIsDelete(0);
    		        } 
    				item.setUpdateAt(new Date());
    				item.setGroupType(1);
    				item.setGroupId(0l);
    				item.setState(1);
    				deviceGroupService.saveOrUpdate(item);
    			}
    		}
    	   return R.ok(device);
    	 }
    	return R.error("数据错误");
    }
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "更新", response = Boolean.class)
    @PostMapping("/edit")
    @PreAuthorize("@ss.hasPermi('iot:device:update')")
    public R<DeviceVO> edit(@Valid @RequestBody DeviceVO device){
   		device.setUpdateAt(new Date());
   		if(device.getDeviceTypeId()!=null) {
   			DeviceTypeEntity deviceType =deviceTypeService.getById(device.getDeviceTypeId());
 			if(deviceType!=null) {
 				device.setDeviceType(deviceType.getType());
 				device.setDeviceTypeName(deviceType.getName());
 				if(device.getId()==null) {
 	 				deviceType.setTotalSum(deviceType.getTotalSum()+1);
 	 	 			deviceTypeService.updateById(deviceType);
 	 			}
 			}
 		}
// 		if(device.getCateId()!=null) {
// 			CategoryEntity monitorCategory =monitorCategoryService.getById(device.getCateId());
// 			if(monitorCategory!=null) {
// 				device.setCateName(monitorCategory.getName());
// 			}
// 		}
 		if(device.getProductId()!=null) {
 			ProductEntity product =productService.getById(device.getProductId());
 			if(product!=null) {
 				device.setProductName(product.getProductName());
 			}
 		}
   		
    	if(deviceService.updateById(device)) {
    		List<DevicePropertyDataEntity> devicePropertyDataList=device.getDevicePropertyDataList();
    		for(DevicePropertyDataEntity item:devicePropertyDataList) {
    				item.setDeviceId(device.getId());
    				if(item.getId()==null) {
    					item.setCreateAt(new Date());
    					item.setIsDelete(0);
    		        } 
    				item.setUpdateAt(new Date());
        	}
    		devicePropertyDataService.saveOrUpdateBatch(devicePropertyDataList);
    		
    			List<DeviceGroupVO>  deviceGroupVOs=device.getDeviceGroupVOs();
    			if(deviceGroupVOs!=null&&deviceGroupVOs.size()>0) {
        		deviceGroupService.modState(null,device.getId(),1, 0);
        		for(DeviceGroupVO item:deviceGroupVOs) {
        				item.setDeviceId(device.getId());
        				if(item.getId()==null) {
        					item.setCreateAt(new Date());
        					item.setIsDelete(0);
        		        } 
        				item.setUpdateAt(new Date());
        				item.setUpdateAt(new Date());
        				item.setGroupType(1);
        				item.setGroupId(0l);
        				item.setState(1);
        				deviceGroupService.saveOrUpdate(item);
            	}
    		}
    	  return R.ok(device);
    	 }
    	return R.error("数据错误");
    }
    /**
     * 删除
     */
    @ApiOperation(value = "删除", response = Boolean.class)
    @DeleteMapping("/delete")
    @PreAuthorize("@ss.hasPermi('iot:device:delete')")
    @Log(title = "设备", businessType = BusinessType.DELETE)
    public R<Boolean> delete(@RequestBody Long[] ids){
        return R.ok(deviceService.removeByIds(Arrays.asList(ids)));
    }

}
